<script setup="">
import {onMounted, ref, defineEmits} from "vue"
import {Plus} from "@element-plus/icons-vue"
import {adminGetColumn, adminParseLink, adminPostTweet, adminUpdateTweet} from "@/request/mid_interface.js";
import {ElMessage} from "element-plus";
import axios from "axios";
import {Close} from "@element-plus/icons-vue"

const props = defineProps({
  param: {
    type: Object,
    required: false,
  }
})

const emit = defineEmits(["refresh", "close"]);

onMounted(() => {
  getColumnList()
  if (!props.param || !props.param.tweet_id) {
    releaseTime.value = new Date()
  } else {
    const {
      article_link,
      column_txt,
      cover_image,
      is_pinned,
      post_time,
      title,
      tweet_id
    } = props.param
    tweetID.value = tweet_id
    jumpUrl.value = article_link
    imageUrl.value = cover_image
    articleTitle.value = title
    releaseTime.value = new Date(post_time)
    isSticky.value = is_pinned ? "是" : "否"
    belongColumn.value = column_txt.trim().length === 0 ? [] : column_txt.split(",")
  }
})

const handleAvatarSuccess = (
    response,
    uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
}

const beforeAvatarUpload = (rawFile) => {
  const imgArr = ["image/jpeg", "image/png", "image/gif", "image/bmp", "image/svg+xml", "image/webp"]
  if (imgArr.indexOf(rawFile.type) === -1) {
    ElMessage.error('请上传图片格式的文件')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小请不要超过2MB')
    return false
  }
  return true
}

async function confirmSend() {
  if (!tweetID.value) {
    // 新建发布
    const postParam = {
      url: "",
      head_img: "",
      title: "",
      release_time: "",
      is_sticky: "",
      column: ""
    }
    postParam.url = jumpUrl.value
    postParam.head_img = imageUrl.value
    postParam.title = articleTitle.value
    postParam.release_time = releaseTime.value.getTime()
    postParam.is_sticky = isSticky.value === "是"
    postParam.column = belongColumn.value.join(",")
    const res = await adminPostTweet(postParam)
    if (res.code) {
      ElMessage.success("发布成功！")
      emit('refresh')
    }
  } else {
    // 更新发布
    const postParam = {
      tweet_id: 0,
      url: "",
      head_img: "",
      title: "",
      release_time: "",
      is_sticky: "",
      column: ""
    }
    postParam.tweet_id = tweetID.value
    postParam.url = jumpUrl.value
    postParam.head_img = imageUrl.value
    postParam.title = articleTitle.value
    postParam.release_time = releaseTime.value.getTime()
    postParam.is_sticky = isSticky.value === "是"
    postParam.column = belongColumn.value.join(",").trim() === "," ? "" : belongColumn.value.join(",")
    const res = await adminUpdateTweet(postParam)
    if (res.code) {
      ElMessage.success("编辑成功！")
      emit('refresh')
    } else {
      ElMessage.warning("请将信息填写完整")
    }
  }
}

async function getColumnList() {
  const res = await adminGetColumn()
  columnList.value = res.data.map((e) => {
    return {
      value: e,
      label: e,
    }
  })
}

const fileInput = ref(null)

function uploadImg(e) {
  let formData = new FormData()
  // 在这里写代码，判断文件是否为图片且大小小于2MB
  let file = e.target.files[0]
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.warning("需上传图片文件，且图片大小小于2MB")
    return
  }
  formData.append('file', e.target.files[0])
  axios.post('/api/img/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
      'token': localStorage.token,
    }
  }).then(res => {
    imageUrl.value = res.data.data
    console.log(res.data.data)
  }).catch(error => {
    console.log(error)
  })
}

async function parseLink() {
  if (!jumpUrl.value.startsWith("https://")) {
    ElMessage.warning("请输入正确的文章链接")
    return
  }
  const res = await adminParseLink({
    url: jumpUrl.value,
  })
  const {msg_title, msg_cdn_url} = res.data
  if (msg_title === "" || msg_cdn_url === "") {
    ElMessage.error("解析失败，请重新检查文章链接")
  } else {
    articleTitle.value = msg_title
    imageUrl.value = msg_cdn_url
    ElMessage.success("解析成功")
  }
}

function uploadImgBtn() {
  fileInput.value.click()
}

const columnList = ref([])
const stickyOptions = [
  {
    value: '是',
    label: '是',
  },
  {
    value: '否',
    label: '否',
  },
]

const tweetID = ref(0)
const jumpUrl = ref("")
const imageUrl = ref("")
const articleTitle = ref("")
const releaseTime = ref("")
const isSticky = ref("")
const belongColumn = ref("")

</script>

<template>
  <div class=" px-24 py-8">
    <input type="file" accept="image/*" ref="fileInput" style="display: none" @change="uploadImg">

    <!-- 文章链接 -->
    <div class="flex items-center">
      <div class="w-28">文章链接</div>
      <el-input
          v-model="jumpUrl"
          placeholder="请输入公众号文章链接"
          class=""
          size="large"
      >
        <template #append>
          <el-button @click="parseLink">解析</el-button>
        </template>
      </el-input>
    </div>

    <!-- 请上传头图 -->
    <div class="flex items-center mt-6">
      <div style="width: 94px">请上传头图</div>
      <div class="relative" v-if="imageUrl">
        <el-image
            style="width: 100px; height: 100px"
            :src="imageUrl"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="[imageUrl]"
            :initial-index="4"
            fit="cover"
        />
        <div @click="imageUrl=''" class="cursor-pointer absolute right-1 top-1 w-5 h-5 flex justify-center items-center"
             style="background: rgba(0,0,0,0.3)">
          <el-icon color="white">
            <Close/>
          </el-icon>
        </div>
      </div>
      <div @click="uploadImgBtn" v-if="!imageUrl"
           class="w-24 h-24 flex justify-center items-center bg-gray-100 rounded">
        <el-icon class="" style="">
          <Plus/>
        </el-icon>
      </div>
    </div>

    <!-- 文章标题 -->
    <div class="flex items-center mt-6">
      <div class="w-28">文章标题</div>
      <el-input
          v-model="articleTitle"
          placeholder="请输入文章的标题"
          class=""
          size="large"
      >
      </el-input>
    </div>

    <!-- 发布时间 -->
    <div class="flex items-center mt-6">
      <div style="width: 94px">发布时间</div>
      <el-date-picker
          v-model="releaseTime"
          class="flex-1"
          size="large"
          type="datetime"
          placeholder="请选择发布时间"
          format="YYYY/MM/DD HH:mm:ss"
      />
    </div>

    <!-- 是否置顶 -->
    <div class="flex items-center mt-6">
      <div style="width: 94px">是否置顶</div>
      <el-select
          v-model="isSticky"
          class="m-2 flex-1"
          placeholder="请选择是否置顶"
          size="large"
      >
        <el-option
            v-for="item in stickyOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
    </div>

    <!-- 归属专栏 -->
    <div class="flex items-center mt-6">
      <div style="width: 94px">归属专栏</div>
      <el-select
          v-model="belongColumn"
          multiple
          filterable
          size="large"
          allow-create
          default-first-option
          :reserve-keyword="false"
          placeholder="请选择归属专栏"
          class="flex-1"
      >
        <el-option
            v-for="item in columnList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
    </div>

    <div class="flex justify-center mt-16">
      <div @click="emit('close')"
           class="cursor-pointer select-none hover:opacity-70 px-5 py-2 border rounded font-bold">取消
      </div>
      <div @click="confirmSend"
           class="cursor-pointer select-none hover:opacity-70 px-5 py-2 border rounded font-bold ml-3 text-white"
           style="background: var(--themeColor); border: var(--themeColor);">确认保存
      </div>
    </div>

  </div>
</template>

<style scoped>
* {
  --el-pagination-hover-color: var(--themeColor);
  --el-input-focus-border-color: var(--themeColor);
}

/deep/ .el-dialog {
  border-radius: 20px;
}

/deep/ .m-2 {
  margin: 0;
}

/deep/ .el-input__wrapper {
  box-shadow: 0 0 0 1px #eee inset;
}

/deep/ .el-select__wrapper {
  box-shadow: 0 0 0 1px #eee inset;
}

/deep/ .el-input-group__append {
  transform: translateX(-1px);
  box-shadow: 0 0 0 1px #eee inset;
}
</style>
